import React, { useCallback, useEffect, useMemo, useState } from "react";
import { LibAppView as AppView, Validation } from "../../lib";
import { PageWrapper } from "./Layout/Desktop/PageWrapper";
import { AdminReducer, AdminLayoutReducer } from "./data/reducer";
import { JourneyApp } from "./data/journeyApp";
import { Skeleton, App } from "antd";
import { utils } from "elmer-common";
import { ApiProvider } from "./Component/Api";
import Api from "./Api";
import { Desktop } from "./Layout/Desktop";
import { AdminApiHandler } from "./Component/AdminHandler";
const { StateProvider } = AdminReducer;
const { useViewState } = AdminLayoutReducer;

interface IAdminLoadResponse {
    loginStatus?: any;
    websiteConfig?: any;
}

const AdminWrapper = () => {
    const layoutState = useViewState();
    const app = AppView.useApp();
    const i18n = AppView.useI18n();
    const antApp = App.useApp();
    const [ loading, setLoading ] = useState(false);
    const skeletonLoading = useMemo(() => {
        return loading && utils.isEmpty(layoutState.state.systemName)
    }, [loading, layoutState.state]);
    const formatMenuData = useCallback((listData: any[]) => {
        return listData.map((item) => {
            const subItems: any[] = item.items?.length > 0 ? formatMenuData(item.items) : [];
            return {
                label: item.name,
                icon: item.icon,
                pathname: item.pathname,
                value: item.id,
                module: item.module,
                status: item.status == 1,
                items: subItems
            }
        });
    }, []);
    const loadMenu = useCallback(() => {
        setLoading(true);
        app.serviceApi.send({
            endPoint: "menus.fullList",
            data: {
                module: "Admin"
            }
        }).then(({ data }: any) => {
            const menuData = formatMenuData(data);
            layoutState.setState({
                systemMenus: menuData
            }, {
                type: "Update_System_Menu"
            });
            setLoading(false);
        }).catch((err) => {
            setLoading(false);
            (typeof err !== "boolean") && antApp?.message?.error(err?.message);
        });
    }, []);
    const loadI18n = useCallback(() => {
        setLoading(true);
        app.serviceApi.send({
            endPoint: "setting.langaugeList",
            data: {
                module: "Admin"
            }
        }).then(({ data }: any) => {
            const listData: any[] = data || [];
            const i18nData: any = {
                "en-GB": {},
                "zh-CN": {}
            };
            setLoading(false);
            listData.forEach((item: any) => {
                const localeEnGb = item.en_gb;
                const localeCnZh = item.cn_zh;
                const localeKey = item.name;
                i18nData["en-GB"][localeKey] = localeEnGb;
                i18nData["zh-CN"][localeKey] = localeCnZh;
            });
            i18n.updateMessages(i18nData);
            localStorage.setItem("i18n",JSON.stringify(i18nData));
            console.log(i18nData);
        }).catch((err) => {
            console.error(err);
            setLoading(false);
        })
    }, []);
    const refreshTheme = useCallback(() => {
        return localStorage.getItem("theme") || "light";
    }, []);
    const [ ApiProvider ] = useState(() =>Api.createProvider({
        refreshMenu: () => loadMenu(),
        refreshI18n: () => loadI18n(),
        refreshTheme: () => refreshTheme()
    }));
    useEffect(() => {
        const defaultData = localStorage.getItem("i18n");
        loadMenu();
        if(!defaultData || utils.isEmpty(defaultData)){
            loadI18n();
        } else {
            i18n.updateMessages(JSON.parse(defaultData));
        }
        
    }, []);
    return (
        <ApiProvider>
            <Skeleton active={false} loading={skeletonLoading}>
                <AppView.ScreenMedia Desktop={Desktop} Mobile={Desktop} >
                    <PageWrapper />
                </AppView.ScreenMedia>
            </Skeleton>
        </ApiProvider>
    );
};

const Admin = AppView.withService<{}, IAdminLoadResponse>({
    reqMode: "QueueList",
    reqEndPoints: [{
        name: "loginStatus",
        endPoint: "login.status",
        retryCount: 5,
        shouldRetry: (err: any) => err.statusCode === "Redis_Timeout"
    }, {
        name: "websiteConfig",
        endPoint: "setting.configWebsite"
    }],
    "loadingOptions": {
        "mountWithLoading": true
    }
})((props) => {
    const app = AppView.useApp();
    useEffect(() => {
        if(props.responseData?.afterApiResponse) {
            if(!/^200$/.test(props.responseData.loginStatus?.statusCode)) {
                app.goto("home.login");
            }
            if(/^200$/.test(props.responseData.websiteConfig?.statusCode)) {
                sessionStorage.setItem("websiteConfig", JSON.stringify(props.responseData.websiteConfig.data));
            }
        }
    }, [props.responseData]);

    return (<StateProvider>
        <JourneyApp.Provider>
            <ApiProvider>
                {!props.withLoadingApi.visible && <AdminWrapper /> }
            </ApiProvider>
        </JourneyApp.Provider>
    </StateProvider>);
});

const AdminView = () => {
    return <AdminApiHandler>
        <Admin />
    </AdminApiHandler>
};

export default AdminView;
